import { expect } from '@jest/globals';
import fsExtra from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion, CaseLevel, IsEnable,
  RuntimeOSType,
  SDKType, SignType
} from '../../plugins/project-builder/models/constants';
import { ProjectTemplateOptionBuilder } from '../../plugins/project-builder/models/model-options';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: ProjectTemplateOptionBuilder.builder()
    .sdk(SDKType.Single)
    .apiType(APIType.FA)
    .apiVersion(APIVersion.API11)
    .abilityType(AbilityType.Application)
    .runtimeOS(RuntimeOSType.HarmonyOS)
    .build()
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder
  .builder()
  .caseLevel(CaseLevel.L1)
  .sign(SignType.NoSign)
  .ohpmInstall(IsEnable.Enable)
  .build();


const testFun: (module: string) => TestCaseFun = (module: string) => async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const entryModulePath = project.getModule(module).moduleRootPath();
  const manifestJsonPath =
    path.resolve(entryModulePath, 'build/default/intermediates/loader_out/default/ets/MainAbility/manifest.json');

  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
    , ...(module ? { module: `${module}@default` } : {})
  });
  
  const result = await runHvigorAsync(projectRoot, commands);
  const buildPathExist =
    await fsExtra.pathExists(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.hap'));
  const manifestJsonExist = fsExtra.existsSync(manifestJsonPath);

  record.addStep('执行hap编译构建', result);
  expect(buildPathExist).toBe(true);
  expect(manifestJsonExist).toBe(true);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_HOS_FA_Service_Project_build_api11_copy_resource')
  .description('fa模型拷贝静态资源后manifest.json必须存在')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testFun('entry'))
  .load();